import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import random

sender = '17713784536@163.com'  # 填写发信人的邮箱账号
password = 'NYWPDTHKHZBIGGIE'  # 发件人邮箱授权码
# receiver = 'che_huan@qq.com'  # 收件人邮箱账号

class SendEmail:
    def __init__(self,receiver):
        self.sender = sender
        self.receiver = receiver
        self.password = password

    def load_message(self):
        verification_code = self.generate_verification()
        text = f'验证码为：{verification_code}'
        message = MIMEText(text, 'plain', 'utf-8')  # 填写邮件内容
        message['From'] = formataddr(["tracy", self.sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
        message['To'] = formataddr(["test", self.receiver])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
        message['Subject'] = "注册验证码"  # 邮件的主题，也可以说是标题
        return message, verification_code

    def send_email(self):
        message, verification_code = self.load_message()
        server = smtplib.SMTP_SSL("smtp.163.com", 465)  # 发件人邮箱中的SMTP服务器
        server.login(self.sender, self.password)  # 括号中对应的是发件人邮箱账号、邮箱授权码
        server.sendmail(self.sender, [self.receiver, ], message.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()  # 关闭连接
        return verification_code

    def generate_verification(self):
        random_list = list(map(lambda x: random.randint(0, 9), [y for y in range(6)]))
        code = "".join('%s' % i for i in random_list)
        return code

# verification = SendEmail().send_email()
# if verification:
#     print("邮件发送成功")
#     print(f"验证码为：{verification}")
# else:
#     print("邮件发送失败")
